package handling.channel.handler;

import client.BuddyList;
import client.BuddylistEntry;
import client.MapleCharacter;
import client.MapleClient;
import client.MapleLieDetector;
import client.MapleQuestStatus;
import client.PlayerStats;
import client.Skill;
import client.SkillFactory;
import constants.GameConstants;
import constants.ServerConstants;
import handling.channel.ChannelServer;
import handling.channel.PlayerStorage;
import handling.login.LoginServer;
import handling.world.CharacterIdChannelPair;
import handling.world.CharacterTransfer;
import handling.world.MapleMessenger;
import handling.world.MapleMessengerCharacter;
import handling.world.MapleParty;
import handling.world.MaplePartyCharacter;
import handling.world.PartyOperation;
import handling.world.PlayerBuffStorage;
import handling.world.World;
import handling.world.World.Alliance;
import handling.world.World.Buddy;
import handling.world.World.Family;
import handling.world.World.Find;
import handling.world.World.Guild;
import handling.world.World.Messenger;
import handling.world.World.Party;
import handling.world.World.Sidekick;
import handling.world.exped.MapleExpedition;
import handling.world.guild.MapleGuild;
import java.io.PrintStream;
import java.util.List;
import org.apache.log4j.Logger;
import org.apache.mina.core.session.IoSession;
import scripting.AbstractPlayerInteraction;
import scripting.NPCScriptManager;
import server.MapleStatEffect;
import server.ServerProperties;
import server.commands.AdminCommand;
import server.maps.FieldLimitType;
import server.maps.MapleMap;
import server.quest.MapleQuest;
import tools.FileoutputUtil;
import tools.MaplePacket;
import tools.MaplePacketCreator;
import tools.Pair;
import tools.data.LittleEndianAccessor;
import tools.data.input.SeekableLittleEndianAccessor;
import tools.packet.BuddyListPacket;
import tools.packet.FamilyPacket;
import tools.packet.GuildPacket;
import tools.packet.JobPacket;
import tools.packet.LoginPacket;
import tools.packet.MTSCSPacket;
import tools.packet.PartyPacket;
import tools.packet.UIPacket;

public class InterServerHandler {

    private static final Logger log = Logger.getLogger(InterServerHandler.class);
    private static int 职业;

    public static void 拍卖_点击(MapleClient c, MapleCharacter chr) {
        if ((chr.hasBlockedInventory()) || (chr.getMap() == null) || (chr.getEventInstance() != null) || (c.getChannelServer() == null)) {
            c.getSession().write(MaplePacketCreator.serverBlocked(4));
            c.getSession().write(MaplePacketCreator.enableActions());
            return;
        }
        if (chr.getMapId() == 180000001) {
            chr.dropMessage(1, "在这个地方无法使用此功能.");
            c.getSession().write(MaplePacketCreator.enableActions());
            return;
        }
        if (chr.isBanned()) {
            c.getSession().write(MaplePacketCreator.enableActions());
            return;
        }
        if (chr.getAntiMacro().inProgress()) {
            chr.dropMessage(5, "被使用测谎仪时无法操作。");
            c.getSession().write(MaplePacketCreator.enableActions());
            return;
        }
        NPCScriptManager.getInstance().dispose(c);
        NPCScriptManager.getInstance().start(c, 9000086, 55);//点击拍卖打开的NPC:9000086_55
        c.getSession().write(MaplePacketCreator.enableActions());
    }

    public static void 商城_点击(MapleClient c, MapleCharacter chr) {
        if (!chr.isAlive()) {
            c.getPlayer().dropMessage(1, "现在不能进入商城.");
            c.getSession().write(MaplePacketCreator.enableActions());
            return;
        }
        if (chr.isInJailMap()) {
            chr.dropMessage(1, "在这个地方无法使用此功能.");
            c.getSession().write(MaplePacketCreator.enableActions());
            return;
        }
        if (chr.isBanned()) {
            c.getSession().write(MaplePacketCreator.enableActions());
            return;
        }
        if (chr.getAntiMacro().inProgress()) {
            chr.dropMessage(5, "被使用测谎仪时无法操作。");
            c.getSession().write(MaplePacketCreator.enableActions());
            return;
        }
        if ((chr.hasBlockedInventory()) || (chr.getMap() == null) || (chr.getEventInstance() != null) || (c.getChannelServer() == null)) {
            c.getSession().write(MaplePacketCreator.serverBlocked(2));
            c.getSession().write(MaplePacketCreator.enableActions());
            return;
        }
        if (World.getPendingCharacterSize() >= 10) {
            chr.dropMessage(1, "服务器忙，请稍后在试。");
            c.getSession().write(MaplePacketCreator.enableActions());
            return;
        }

        ChannelServer ch = ChannelServer.getInstance(c.getChannel());
        chr.changeRemoval();
        if (chr.getMessenger() != null) {
            MapleMessengerCharacter messengerplayer = new MapleMessengerCharacter(chr);
            World.Messenger.leaveMessenger(chr.getMessenger().getId(), messengerplayer);
        }
        PlayerBuffStorage.addBuffsToStorage(chr.getId(), chr.getAllBuffs());
        PlayerBuffStorage.addCooldownsToStorage(chr.getId(), chr.getCooldowns());
        PlayerBuffStorage.addDiseaseToStorage(chr.getId(), chr.getAllDiseases());
        World.ChannelChange_Data(new CharacterTransfer(chr), chr.getId(), -10);
        ch.removePlayer(chr);
        c.updateLoginState(3, c.getSessionIPAddress());
        chr.saveToDB(false, false);
        chr.getMap().removePlayer(chr);
        c.getSession().write(MaplePacketCreator.getChannelChange(c, Integer.parseInt(handling.cashshop.CashShopServer.getIP().split(":")[1])));
        c.setPlayer(null);
        c.setReceiving(false);
    }

    public static void Loggedin(int playerid, MapleClient c) {
        ChannelServer channelServer = c.getChannelServer();

        CharacterTransfer transfer = channelServer.getPlayerStorage().getPendingCharacter(playerid);
        boolean loggedin = true;

        long loadCharTime = System.currentTimeMillis();
        MapleCharacter player;
        if (transfer == null) {
            System.out.println("载入角色数据前");
            player = MapleCharacter.loadCharFromDB(playerid, c, true);//载入角色的基本属性信息
            System.out.println("载入角色数据后");
            System.out.println(new StringBuilder().append("角色信息加载完成 耗时: ").append((System.currentTimeMillis() - loadCharTime) / 1000L).append(" 秒..").toString());

            Pair ip = LoginServer.getLoginAuth(playerid);
            String s = c.getSessionIPAddress();
            if ((ip == null) || (!s.substring(s.indexOf(47) + 1, s.length()).equals(ip.left))) {
                if (ip != null) {
                    LoginServer.putLoginAuth(playerid, (String) ip.left, (String) ip.right);
                }
                System.err.println("there 163");
                c.getSession().close(true);
                log.info(new StringBuilder().append("检测连接地址 - 1 ").append(s).toString());
                if (ServerProperties.IsLvkejian()) {
                    String SendTo = new StringBuilder().append("\r\n时间：").append(FileoutputUtil.CurrentReadable_Time()).append("  对玩家进行掉线处理 ----20 ").toString();
                    FileoutputUtil.packetLog("log\\玩家进行掉线处理.log", SendTo);
                }
                return;
            }
            c.setTempIP((String) ip.right);
        } else {
            player = MapleCharacter.ReconstructChr(transfer, c, true);
            loggedin = false;
        }
        c.setPlayer(player);
        c.setAccID(player.getAccountID());
        if (!c.CheckIPAddress()) {
            System.err.println("there 180");
            c.getSession().close(true);
            log.info(new StringBuilder().append("检测连接地址 - 2 ").append(!c.CheckIPAddress()).toString());
            if (ServerProperties.IsLvkejian()) {
                String SendTo = new StringBuilder().append("\r\n时间：").append(FileoutputUtil.CurrentReadable_Time()).append("  对玩家进行掉线处理 ----21 ").toString();
                FileoutputUtil.packetLog("log\\玩家进行掉线处理.log", SendTo);
            }
            return;
        }
        int state = c.getLoginState();
        boolean allowLogin = false;
        if ((state == 1) || (state == 3) || (state == 0)) {
            allowLogin = !World.isCharacterListConnected(c.loadCharacterNames(c.getWorld()));
        }
        if (!allowLogin) {
            c.setPlayer(null);
            System.err.println("there 196");
            c.getSession().close(true);
            log.info(new StringBuilder().append("检测连接地址 - 3 ").append(!allowLogin).toString());
            if (ServerProperties.IsLvkejian()) {
                String SendTo = new StringBuilder().append("\r\n时间：").append(FileoutputUtil.CurrentReadable_Time()).append("  对玩家进行掉线处理 ----22 ").toString();
                FileoutputUtil.packetLog("log\\玩家进行掉线处理.log", SendTo);
            }
            return;
        }
        c.updateLoginState(2, c.getSessionIPAddress());
        channelServer.addPlayer(player);
        player.giveCoolDowns(PlayerBuffStorage.getCooldownsFromStorage(player.getId()));
        player.silentGiveBuffs(PlayerBuffStorage.getBuffsFromStorage(player.getId()));
        player.giveSilentDebuff(PlayerBuffStorage.getDiseaseFromStorage(player.getId()));

        c.getSession().write(LoginPacket.去头顶称号_0());
        c.getSession().write(MaplePacketCreator.getCharInfo(player));//WARP_TO_MAP

        c.getSession().write(MTSCSPacket.enableCSUse());
        c.getSession().write(MaplePacketCreator.发送登陆成功());
        c.getSession().write(MaplePacketCreator.updateMount(player, false));

        if ((ServerProperties.IsLvkejian()) && (player.isLvkejian())) {
            SkillFactory.getSkill(9001004).getEffect(1).applyTo(player);
        }

        c.getSession().write(MaplePacketCreator.temporaryStats_Reset());
        player.getMap().addPlayer(player);
        try {
            int[] buddyIds = player.getBuddylist().getBuddyIds();
            World.Buddy.loggedOn(player.getName(), player.getId(), c.getChannel(), buddyIds);
            if (player.getParty() != null) {
                MapleParty party = player.getParty();
                World.Party.updateParty(party.getId(), PartyOperation.LOG_ONOFF, new MaplePartyCharacter(player));
                if ((party != null) && (party.getExpeditionId() > 0)) {
                    MapleExpedition me = World.Party.getExped(party.getExpeditionId());
                    if (me != null) {
                        c.getSession().write(PartyPacket.expeditionStatus(me, false));
                    }
                }
            }
            if (player.getSidekick() == null) {
                player.setSidekick(World.Sidekick.getSidekickByChr(player.getId()));
            }
            if (player.getSidekick() != null) {
                c.getSession().write(PartyPacket.updateSidekick(player, player.getSidekick(), false));
            }
            CharacterIdChannelPair[] onlineBuddies = World.Find.multiBuddyFind(player.getId(), buddyIds);
            for (CharacterIdChannelPair onlineBuddy : onlineBuddies) {
                player.getBuddylist().get(onlineBuddy.getCharacterId()).setChannel(onlineBuddy.getChannel());
            }
            c.getSession().write(BuddyListPacket.updateBuddylist(player.getBuddylist().getBuddies()));

            MapleMessenger messenger = player.getMessenger();
            if (messenger != null) {
                World.Messenger.silentJoinMessenger(messenger.getId(), new MapleMessengerCharacter(player));
                World.Messenger.updateMessenger(messenger.getId(), player.getName(), c.getChannel());
            }

            if (player.getGuildId() > 0) {
                World.Guild.setGuildMemberOnline(player.getMGC(), true, c.getChannel());
                c.getSession().write(GuildPacket.showGuildInfo(player));
                MapleGuild gs = World.Guild.getGuild(player.getGuildId());
                if (gs != null) {
                    List<byte[]> packetList = World.Alliance.getAllianceInfo(gs.getAllianceId(), true);
                    if (packetList != null) {
                        for (byte[] pack : packetList) {
                            if (pack != null) {
                                c.getSession().write(pack);
                            }
                        }
                    }
                } else {
                    player.setGuildId(0);
                    player.setGuildRank((byte) 5);
                    player.setAllianceRank((byte) 5);
                    player.saveGuildStatus();
                }
            }

            if (player.getFamilyId() > 0) {
                World.Family.setFamilyMemberOnline(player.getMFC(), true, c.getChannel());
            }
            c.getSession().write(FamilyPacket.getFamilyData());
            c.getSession().write(FamilyPacket.getFamilyInfo(player));
        } catch (Exception e) {
            FileoutputUtil.outputFileError("log\\Login_Error.log", e);
        }

        player.getClient().getSession().write(MaplePacketCreator.serverMessage(channelServer.getServerMessage()));

        player.sendMacros();

        player.showNote();

        player.sendImp();

        player.updatePartyMemberHP();

        player.startFairySchedule(false);

        player.baseSkills();
        
        //player.dlqcheck();

        c.getSession().write(MaplePacketCreator.getKeymap(player.getKeyLayout(), 职业));

        c.getSession().write(MaplePacketCreator.显示背包抵用券(player));

        player.updatePetAuto();
        c.getSession().write(MaplePacketCreator.reportResponse((byte) 0, 0));
        c.getSession().write(MaplePacketCreator.enableReport());

        player.expirationTask(true, transfer == null);

        if (player.getJob() == 132) {
            player.checkBerserk();
        }
        player.spawnClones();

        player.spawnSavedPets();
        if (player.getStat().equippedSummon > 0) {
            SkillFactory.getSkill(player.getStat().equippedSummon).getEffect(1).applyTo(player);
        }

        MapleQuestStatus stat = player.getQuestNoAdd(MapleQuest.getInstance(122700));
        c.getSession().write(MaplePacketCreator.pendantSlot((stat != null) && (stat.getCustomData() != null) && (Long.parseLong(stat.getCustomData()) > System.currentTimeMillis())));

        stat = player.getQuestNoAdd(MapleQuest.getInstance(123000));
        c.getSession().write(MaplePacketCreator.quickSlot((stat != null) && (stat.getCustomData() != null) && (stat.getCustomData().length() == 8) ? stat.getCustomData() : null));

        if (loggedin) {
            String msg = new StringBuilder().append("#r").append(player.getVipname(2)).append(" #d").append(player.getName()).append(" #k").append("  \r\n欢迎来到 ").append(c.getChannelServer().getServerName()).append(" ！\r\n当前服务端版本为: [Ver.#b").append(ServerConstants.MAPLE_VERSION).append(".").append(ServerConstants.MAPLE_PATCH).append("#k] 您已经成功进入游戏！\r\n在对话框输入 #r@help #k可以查看您当前能使用的命令!\r\n#b祝您游戏愉快！\r\n\r\n               By: #r六月").toString();
            c.getPlayer().dropMessage(5, "欢迎来到" + c.getChannelServer().getServerName() + " 在对话框输入 @help 可以查看您当前能使用的命令  @hg可以回到自由市场  祝您游戏愉快！");
           // World.Broadcast.broadcastMessage(UIPacket.clearMidMsg());
            //World.Broadcast.broadcastMessage(UIPacket.getMidMsg( "我们的家人 " + "：【" + c.getPlayer().getName() + " 】來到了" + c.getChannelServer().getServerName() + "世界！我们一起和睦相处吧。", true, 0));
        //    World.Broadcast.broadcastMessage(MaplePacketCreator.发送玩家带颜色背景公告(-1, "[上线提示] " + "我的家人：" + c.getPlayer().getName() + " 來到了" + c.getChannelServer().getServerName() + "世界！大家一起和睦相处吧。"));
            c.getSession().write(MaplePacketCreator.serverNotice(1, "欢迎【" + c.getPlayer().getName() + "】来到 " + c.getChannelServer().getServerName() + "！\r\n您的账号为: " + c.getAccountName() + "\r\n请记牢您的账号，妥善保管您的密码\r\n我们的官网是www.66mxd.com\r\n请不要相信GM以外的人避免上当受骗\r\nGM在此祝您游戏愉快"));
          //  MaplePacketCreator.玩家头顶提示("亲爱的" + c.getPlayer().getName() + "。你已成功进入游戏,目前版本为Ver. " + ServerConstants.MAPLE_VERSION + " . " + ServerConstants.MAPLE_PATCH + "，如有问题，请联系" + c.getChannelServer().getServerName() + "客服！", 550, 5);
            player.getHyPay(1);
            if (player.getLevel() == 1) {
                // player.dropMessage(1, new StringBuilder().append("欢迎来到 ").append(c.getChannelServer().getServerName()).append(", ").append(player.getName()).append(" ！\r\n使用 @help 可以查看您当前能使用的命令！\r\n祝您玩的愉快！").toString());
                // player.dropMessage(5, "使用 @help 可以查看您当前能使用的命令 祝您玩的愉快！");
                c.getSession().write(MaplePacketCreator.serverNotice(1, "欢迎【" + c.getPlayer().getName() + "】来到 " + c.getChannelServer().getServerName() + "！\r\n您的账号为: " + c.getAccountName() + "\r\n请记牢您的账号，妥善保管您的密码\r\n我们的官网是www.66mxd.com\r\n请不要相信六月以外的人避免上当受骗\r\n六月在此祝您游戏愉快"));
                World.Broadcast.broadcastMessage(MaplePacketCreator.serverNotice(26, "[上线提示] " + "玩家：" + c.getPlayer().getName() + " 來到了" + c.getChannelServer().getServerName() + "世界！"));
            } else {
                 //c.getSession().write(MaplePacketCreator.sendHint(msg, 200, 30));//缺少这个类
            }

            if (c.getChannelServer().getDoubleExp() == 2) {
                player.dropMessage(5, "当前服务器处于双倍经验活动中，祝您玩的愉快！");
            }

        }

        if ((GameConstants.is尖兵(player.getJob())) && (player.getJob() != 3002)) {
            c.getSession().write(JobPacket.XenonPacket.尖兵能量时间(player.尖兵能量电池状态(), player.尖兵能量电池最大时间(true), player.尖兵能量电池剩余时间()));
            c.getSession().write(JobPacket.XenonPacket.尖兵能量补给(player.尖兵能量()));
        } else if ((GameConstants.is夜光(player.getJob())) && (c.getPlayer().getJob() >= 2710) && (c.getPlayer().getJob() <= 2712)) {
            c.getPlayer().刷新夜光能量信息(20040219, 0);
            int[] ss = {27110007, 27100003};
            for (int i : ss) {
                Skill skil = SkillFactory.getSkill(i);
                if ((skil != null) && (player.getSkillLevel(skil) > 0)) {
                    SkillFactory.getSkill(i).getEffect(1).applyTo(player);
                    if (player.isLvkejian()) {
                        player.dropMessage(new StringBuilder().append("夜光BUFF 检测 技能ID ").append(skil.getId()).append("  名字").append(skil.getName()).append("  技能等级 = ").append(player.getSkillLevel(skil)).toString());
                    }
                    if ((i == 27110007) && (player.getSkillLevel(skil) > 0)) {
                        player.开启夜光生命潮汐(2);
                    } else if ((i == 27100003) && (player.getSkillLevel(skil) > 0)) {
                        player.开启夜光黑暗祝福(3);
                    }
                }
            }
        } else if ((GameConstants.is狂龙(player.getJob())) && (c.getPlayer().getJob() >= 6110) && (c.getPlayer().getJob() <= 6112)) {
            player.刷新狂龙能量(1, !player.isLvkejian());
        } else if (GameConstants.is恶魔复仇者(player.getJob())) {
            player.刷新恶魔复仇者攻击力();
        } else if (GameConstants.is冒险家(player.getJob())) {
            if (player.isLvkejian()) {
                player.dropMessage("冒险家4转技能 最大等级刷新 开始");
            }
            player.刷新职业四转技能最大等级();
            if (GameConstants.is主教(player.getJob())) {
                Skill skil = SkillFactory.getSkill(2300009);
                if ((skil != null) || (player.getSkillLevel(skil) > 0)) {
                    if (player.isLvkejian()) {
                        player.dropMessage(new StringBuilder().append("主教BUFF 检测 技能ID ").append(skil.getId()).append("  名字").append(skil.getName()).append("  技能等级 = ").append(player.getSkillLevel(skil)).toString());
                    }
                    SkillFactory.getSkill(2300009).getEffect(skil.getMaxLevel()).applyTo(player);
                }
            }
            if (player.isLvkejian()) {
                player.dropMessage("冒险家4转技能 最大等级刷新 完成");
            }
            if (player.getLevel() < 10) {
                player.播放动漫("冒险家开场", true);
                player.setLevel((short) 10);
                player.levelUp();
                if (player.getExp() < 0L) {
                    player.gainExp(-player.getExp(), false, false, true);
                }
            }
        } else if (GameConstants.is神之子(player.getJob())) {
            if (player.getLevel() <= 100) {
                player.播放动漫("神之子开场2", true);
                player.setLevel((short) 101);
                player.levelUp();
                if (player.getExp() < 0L) {
                    player.gainExp(-player.getExp(), false, false, true);
                }
            }
            player.完成_神之子_剧情任务();
        }

        player.恶魔转职检测();

        c.getSession().write(MaplePacketCreator.getInventoryStatus());

        player.完成一些系统任务();
    }

    public static void ChangeChannel(LittleEndianAccessor slea, MapleClient c, MapleCharacter chr) {
        if ((chr == null) || (chr.hasBlockedInventory()) || (chr.getEventInstance() != null) || (chr.getMap() == null) || (chr.isInBlockedMap()) || (FieldLimitType.ChannelSwitch.check(chr.getMap().getFieldLimit()))) {
            c.getSession().write(MaplePacketCreator.enableActions());
            return;
        }
        if (chr.isBanned()) {
            c.getSession().write(MaplePacketCreator.enableActions());
            return;
        }
        if (chr.getAntiMacro().inProgress()) {
            chr.dropMessage(5, "被使用测谎仪时无法操作。");
            c.getSession().write(MaplePacketCreator.enableActions());
            return;
        }
        if (World.getPendingCharacterSize() >= 10) {
            chr.dropMessage(1, "服务器忙，请稍后在试。");
            c.getSession().write(MaplePacketCreator.enableActions());
            return;
        }
        int chc = slea.readByte() + 1;
        if (!World.isChannelAvailable(chc)) {
            chr.dropMessage(1, "该频道玩家已满，请切换到其它频道进行游戏。");
            c.getSession().write(MaplePacketCreator.enableActions());
            return;
        }
        chr.changeChannel(chc);
    }
}

